import axios, {AxiosInstance} from 'axios'

class axiosManager {
    private readonly axiosInstance:AxiosInstance;
    constructor(baseUrl:string) {
        this.axiosInstance = axios.create({
            baseURL: baseUrl,
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }

    public build() : AxiosObject {
        this.requestInterceptor();
        this.responseInterceptor();
        return {
            get: async (url: string, options: {params?: URLSearchParams}) : Promise<any> => {
                try {
                    return await this.axiosInstance.get(url, options);
                } catch (err) {
                    throw err;
                }
            },
            post: async (url: string, data: any) : Promise<any> => {
                try {
                    return await this.axiosInstance.post(url, data);
                } catch (err) {
                    throw err;
                }
            }

        }
    }

    // 请求拦截器
    private requestInterceptor() : void {
        if (this.axiosInstance === undefined) return;
        this.axiosInstance.interceptors.request.use(function (config) {
            // 在发送请求之前做些什么，比如添加请求头等操作
            return config;
        }, function (error) {
            throw Promise.reject(error);
        })
    }
    // 响应拦截器
    private responseInterceptor() : void {
        this.axiosInstance.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            return response;
        }, function (error) {
            // 对响应错误做点什么
            throw Promise.reject(error);
        });
    }

}

let entInstance : AxiosObject | null = null;
let addrInstance : AxiosObject | null = null;

const entService = ()=> {
    if (!entInstance) {
        let instance = new axiosManager(window.server.EntBaseURL)
        entInstance = instance.build();
        return entInstance;
    }
    return entInstance;
}

const addrService = () => {
    if (!addrInstance) {
        let instance = new axiosManager(window.server.AddrSegBaseURL)
        addrInstance = instance.build()
        return addrInstance;
    }
    return addrInstance;
}


export {entService, addrService};


